package com.example.accountingapp;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class TotalIncomeActivity extends AppCompatActivity {

    private TextView tvTotalIncome;
    private Button btnClear;
    private DatabaseHelperIncome dbHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_total_income);

        tvTotalIncome = findViewById(R.id.tvTotalIncome);
        btnClear = findViewById(R.id.btnClear);

        dbHelper = new DatabaseHelperIncome(this);
        db = dbHelper.getWritableDatabase();

        updateTotalIncome();

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearTotalIncome();
            }
        });

        db.close();
    }

    private void updateTotalIncome() {
        String query = "SELECT SUM(" + DatabaseContractIncome.IncomeEntry.COLUMN_INCOME + ") FROM " +
                DatabaseContractIncome.IncomeEntry.TABLE_NAME;

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);
        if (cursor.moveToFirst()) {
            double totalIncome = cursor.getDouble(0);
            tvTotalIncome.setText("总收入: " + totalIncome);
        }
        cursor.close();
        db.close();
    }

    private void clearTotalIncome() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DatabaseContractIncome.IncomeEntry.COLUMN_INCOME, 0);

        int rowsAffected = db.update(DatabaseContractIncome.IncomeEntry.TABLE_NAME, values, null, null);

        if (rowsAffected > 0) {
            Toast.makeText(this, "总收入已清零", Toast.LENGTH_SHORT).show();
            updateTotalIncome();
        } else {
            Toast.makeText(this, "清零失败，请重试", Toast.LENGTH_SHORT).show();
        }

        db.close();
    }
    public void goBack(View view) {
        finish();
    }
}
